#include "spi.h"
#include "gd32e10x.h"

void spi0_msp_init()
{

}
uint16_t spi_data_transmit_receive_buf(uint32_t spi_periph,uint8_t *pTxData,uint8_t *pRxData,uint16_t len,uint32_t timeout)
{
    uint32_t time_out = 65535;
    uint16_t timeout_cnt;
    uint8_t is_data_frame_16bit;
    if(((spi_periph+0x00U) & SPI_CTL0_FF16))
    {
        //data frame format = 16bit
        is_data_frame_16bit = 1;
    }
    else
    {
        //data frame format = 8bit
        is_data_frame_16bit = 0;
    }
    
    while(len--)
    {
        time_out = timeout;
        
        if(is_data_frame_16bit)
        {
            spi_i2s_data_transmit(spi_periph,*((uint16_t *)(pTxData)));
            while(spi_i2s_flag_get(spi_periph,SPI_FLAG_TRANS) == RESET || (time_out--) == 0);
            pTxData += sizeof(uint16_t);
            
            if(time_out != 0) 
            {
                *(pRxData) = (uint16_t)spi_i2s_data_receive(spi_periph);
                pRxData += sizeof(uint16_t);
            }
            else
            {
                timeout_cnt++; //spi timeout
            }
        }
        else
        {
            spi_i2s_data_transmit(spi_periph,*((uint8_t *)(pTxData)));
            while(spi_i2s_flag_get(spi_periph,SPI_FLAG_TRANS) == RESET || (time_out--) == 0);
            pTxData += sizeof(uint8_t);
            
            if(time_out != 0) 
            {
                *(pRxData) = (uint8_t)spi_i2s_data_receive(spi_periph);
                pRxData += sizeof(uint8_t);
            }
            else
            {
                timeout_cnt++; //spi timeout
            }
        }
    }
    
    return timeout_cnt;
}

uint16_t spi_data_transmit_buf(uint32_t spi_periph,uint8_t *pTxData,uint16_t len,uint32_t timeout)
{
    uint16_t timeout_cnt;

    timeout_cnt = spi_data_transmit_receive_buf(spi_periph,pTxData,pTxData,len,timeout);
    
    return timeout_cnt;
}

uint16_t spi_data_receive_buf(uint32_t spi_periph,uint8_t *pRxData,uint16_t len,uint32_t timeout)
{
    uint16_t timeout_cnt;

    timeout_cnt = spi_data_transmit_receive_buf(spi_periph,pRxData,pRxData,len,timeout);    
    return timeout_cnt;
}

uint16_t spi_data_transmit_receive_buf_DMA(uint32_t spi_periph,uint8_t *pTxData,uint8_t *pRxData,uint16_t len,uint32_t timeout)
{
    uint16_t timeout_cnt;
    return timeout_cnt;
}

uint16_t spi_data_transmit_buf_DMA(uint32_t spi_periph,uint8_t *pTxData,uint8_t *pRxData,uint16_t len,uint32_t timeout)
{
    uint16_t timeout_cnt;
    return timeout_cnt;
}

uint16_t spi_data_receive_buf_DMA(uint32_t spi_periph,uint8_t *pTxData,uint8_t *pRxData,uint16_t len,uint32_t timeout)
{
    uint16_t timeout_cnt;
    return timeout_cnt;
}
